<template>
  <div class="container">
    <el-card>
      <div class="self-left">
        <el-form
          :inline="true"
          :model="formInline"
          class="demo-form-inline left"
        >
          <el-form-item label="关键字">
            <el-input v-model="formInline.keyword"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="formInline.state" placeholder="请选择">
              <el-option label="禁用" value="0"></el-option>
              <el-option label="启用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="cancel">清除</el-button>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="self-right">
        <el-button type="success" icon="el-icon-edit" @click="newlyIncreased" class="oness"
          >新增技巧</el-button
        >
      </div>
      <el-alert
        type="info"
        class="alert"
        :closable="false"
        show-icon
        :title="'数据一共' + all + '条'"
      ></el-alert>
      <!-- 表格 -->
      <el-table
        ref="singleTable"
        :data="tableData"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column width="400" label="文章标题">
          <template slot-scope="scope">
            {{ scope.row.title }}
            <span v-if="scope.row.videoURL !== null">
              <i
                class="el-icon-film red"
                @click="seeAmovie(scope.row.videoURL)"
              ></i>
            </span>
          </template>
        </el-table-column>
        <el-table-column width="20"> </el-table-column>
        <el-table-column property="visits" label="阅读人数" width="230">
        </el-table-column>
        <el-table-column property="username" label="录入人" width="180">
        </el-table-column>
        <el-table-column property="createTime" label="录入时间">
          <!-- 格式化时间 -->
          <template slot-scope="scope">
            {{ _timeTimeOfEntry(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column property="state" label="状态">
          <!-- 格式化状态 -->
          <template slot-scope="scope">
            {{ _hireformOfEmployment(scope.row.state) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 插槽 -->
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >预览</el-button
            >
            <el-button type="text" size="small" @click="amend(scope.row)">{{
              scope.row.state == 1 ? "禁用" : "启用"
            }}</el-button>
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.state === 0"
              @click="modifyData(scope.row)"
              >修改</el-button
            >
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.state === 0"
              @click="del(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 换页按钮 -->
      <div class="block">
        <el-pagination
        class="boxxx"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="all"
        >
        </el-pagination>
      </div>

      <!-- 弹框看电影 -->
      <div class="box" v-if="dialogVisible">
        <video :src="video" controls autoplay class="box2"></video>
        <div @click="dialogVisible = false" class="xxx">
          <i class="el-icon-close boxx"></i>
        </div>
      </div>

      <!-- 弹窗预览文章 -->
      <el-dialog title="预览文章" :visible.sync="articleDialog" width="50%">
        <strong
          v-html="TheArticleDetails.title"
          style="font-size: 25px"
        ></strong>
        <div style="font-size: 18px; padding-top: 8px">
          <span>{{ _timeTimeOfEntry(TheArticleDetails.createTime) }}</span>
          <span style="padding-left: 15px">{{
            TheArticleDetails.username
          }}</span>
          <i class="el-icon-view" style="padding-left: 15px"></i>
          <span>{{ TheArticleDetails.visits }}</span>
        </div>
        <div v-html="TheArticleDetails.articleBody"></div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="articleDialog = false"> 关 闭 </el-button>
        </span>
      </el-dialog>

      <!-- 新增 -->
      <el-dialog title="新增文章" :visible.sync="addDialog" width="40%">
        <!-- 表单验证 -->
        <el-form
          :model="Body"
          :rules="rules"
          ref="Body"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="Body.title"></el-input>
          </el-form-item>
          <el-form-item label="文章标题" prop="title">
            <div id="container">

            </div>

            <span v-if="onfouces" class="reds">请输入内容</span>
          </el-form-item>
          <el-form-item label="视频地址">
            <el-input v-model="Body.videoURL"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialog = false">取 消</el-button>
          <el-button type="primary" @click="newSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { list, deletedData, changeState, addlist, modifyID } from '@/api/acticlsAPI'
import EmployeeEnum from '@/api/base/baseApi'
import formatDate from 'dayjs'
import E from 'wangeditor'
export default {
  data () {
    return {
      // 视频播放
      video: '',
      // 数据条数
      // 数据数组
      tableData: [],
      currentPage: 1,
      currentChange: 1,
      all: 0,
      pagesize: 10,
      forBidden: true,
      formInline: {
        keyword: '',
        state: null
      },
      // 富文本编辑器
      Body: {
        title: '',
        articleBody: '',
        videoURL: '',
        id: null
      },
      // 新增表单校验
      rules: {
        title: [{ required: true, message: '请输入文章标签', trigger: 'blur' }]
      },
      // 视频显示隐藏
      dialogVisible: false,
      // 文章弹窗
      articleDialog: false,
      // 文章详情
      TheArticleDetails: {},
      // 新增
      addDialog: false,
      // 失去焦点，长度为0
      onfouces: false
    }
  },

  created () {
    this.hlist()
  },

  methods: {
    // 修改数据
    modifyData (val) {
      this.addDialog = true
      this.Body = { ...val }
      console.log(val)
      this.$nextTick(() => {
        this.initEditor()
        this.setContent()
      })
    },
    // 点击查询 查询数据
    async onSubmit () {
      console.log('formInline', this.formInline)
      const res = await list({
        page: this.currentPage,
        pagesize: this.pagesize,
        state: this.formInline.state,
        keyword: this.formInline.keyword
      })
      console.log('搜索到的数据', res)
      this.all = res.data.counts
      this.tableData = []
      this.tableData = res.data.items
      console.log('submit!')
    },
    // 点击清除 清除数据，从新获取列表
    cancel () {
      this.formInline = {}
      this.hlist()
    },
    // 获取到的数据
    async hlist () {
      const res = await list({
        page: this.currentChange,
        pagesize: this.pagesize
      })
      console.log('获取到的数据', res.data.items)
      console.log('总条数', res.data.counts)

      this.tableData = res.data.items
      this.all = res.data.counts
    },
    // 切换每一页的总条数
    async handleSizeChange (val) {
      console.log('1122', val)
      this.pagesize = val
      // 更新数据
      const res = await list({
        page: this.currentPage,
        pagesize: this.pagesize,
        state: this.formInline.state,
        keyword: this.formInline.keyword
      })
      console.log('搜索到的数据', res)
      this.all = res.data.counts
      this.tableData = []
      this.tableData = res.data.items
      console.log('submit!')
    },
    // 切换的每一页数
    async handleCurrentChange (val) {
      console.log('66666', val)
      this.currentChange = val
      const res = await list({
        page: val,
        pagesize: this.pagesize,
        state: this.formInline.state,
        keyword: this.formInline.keyword
      })
      console.log('搜索到的数据', res)
      this.all = res.data.counts
      this.tableData = []
      this.tableData = res.data.items
      console.log('submit!')
    },
    // 更改状态
    _hireformOfEmployment (val) {
      const map = {}
      EmployeeEnum.state.forEach((item) => {
        map[item.id] = item.value
      })
      console.log('状态', val)
      return map[val]
    },
    // 格式化时间
    _timeTimeOfEntry (val) {
      formatDate(val).format('YYYY-MM-DD HH:mm:ss')
      return formatDate(val).format('YYYY-MM-DD HH:mm:ss')
    },
    // 删除数据
    del (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await deletedData(id)
          this.hlist()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 禁用
    forBiddenBtn (val) {
      if (this.forBidden) {
        this.forBidden = false
      } else {
        this.forBidden = true
      }
    },
    // 看电影
    seeAmovie (val) {
      this.video = val
      this.dialogVisible = true
    },
    // 更改用户状态
    async amend (val) {
      console.log('val', val)
      const aaa = val.state === 1 ? 0 : 1
      const res = await changeState({ id: val.id, state: aaa })
      console.log('更新成功', res)
      if (res.data.success) {
        this.$message.success('更新成功')
        if (this.formInline.state) {
          this.hlist()
        } else {
          const res = await list({
            page: this.currentPage,
            pagesize: this.pagesize,
            state: this.formInline.state,
            keyword: this.formInline.keyword
          })
          console.log('搜索到的数据', res)
          this.all = res.data.counts
          this.tableData = []
          this.tableData = res.data.items
          console.log('submit!')
        }
      }
    },
    // 文章详情
    handleClick (val) {
      console.log(val)
      this.TheArticleDetails = val
      this.articleDialog = true
    },
    // 新增
    newlyIncreased () {
      // 如果直接写到当前组件的mounted钩子里只能保证一上来就显示的标签能拿得到，但是dialog由于是后面通过点击某个按钮才显示的
      // 显示之后内部的元素标签才开始渲染 又因为这个渲染本身是异步的，所以最后必须在设置了visible为true之后，还得使用nextTick包裹一下才能保证获得到container
      this.addDialog = true
      this.$nextTick(() => {
        this.initEditor()
      })
    },
    // 初始化编辑器
    initEditor () {
      if (this.editor) return false
      this.editor = new E('#container')
      console.log(this.editor)
      this.editor.config.placeholder = ''

      // 配置 onchange 回调函数
      this.editor.config.onchange = (newHtml) => {
        this.Body.articleBody = newHtml
        if (newHtml.length === 0) {
          this.onfouces = true
        } else {
          this.onfouces = false
        }
      }
      this.editor.config.focus = false
      this.editor.create()
    },
    setContent () {
      console.log('重新赋值')
      this.editor.txt.html('<p>' + this.Body.articleBody + '</p>')
    },
    // 点击确定新增数据
    newSubmit () {
      if (this.Body.id) {
        this.$refs.Body.validate(async (value) => {
          if (value) {
            const res = await modifyID(this.Body)
            console.log('修改文章完成', res)
            this.$message.success('修改成功')
            this.hlist()
            this.addDialog = false
            this.Body = {}
          } else {
            return false
          }
        })
      } else {
        this.$refs.Body.validate(async (value) => {
          if (value) {
            const res = await addlist(this.Body)
            console.log('新增文章完成', res)
            this.$message.success('添加成功')
            this.hlist()
            this.addDialog = false
            this.Body = {}
          } else {
            return false
          }
        })
      }
    }

  }
}
</script>

<style scoped>
/* f=富文本编辑器的自定义样式 */
/* table 样式 */

.self-left {
  float: left;
}
.self-right {
  float: right;
}
.red {
  width: 20px;
  height: 20px;
  color: blue;
}
.container {
  position: relative;
}
.box {
  background-color: rgb(0, 0, 0);
  opacity: 0.9;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 10000;
}
.box2 {
  width: 700px;
  height: 400px;
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 10001;
  margin-top: -200px;
  margin-left: -380px;
}
.xxx {
  background-color: rgb(111, 111, 111);
  height: 50px;
  width: 50px;
  position: absolute;
  left: 47%;
  top: 8%;
  border-radius: 50%;
  color: #fff;
  font-size: 30px;
  padding-left: 5px;
  padding-top: 9px;
}
.boxx {
  margin-top: 0px;
  margin-left: 5px;
}
.reds {
  color: red;
}
.oness{
  float: right;
}
.boxxx{
  text-align: right;
}
</style>
